package com.mmall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Category;
import com.mmall.pojo.Product;
import com.mmall.service.ICategoryService;
import com.mmall.service.IProductService;
import com.mmall.util.DateTimeUtil;
import com.mmall.util.PropertiesUtil;
import com.mmall.vo.ProductDetailVo;
import com.mmall.vo.ProductListVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * Create by lisy on Qingdao
 **/
@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    ProductMapper productMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    ICategoryService iCategoryService;

    public ServerResponse productSaveOrAddService(Product product){
        if(product != null){
            //如果主图为空，将子图中的第一章图片做主图
            if(StringUtils.isNotBlank(product.getSubImages())){
                String[] subImageArray = product.getSubImages().split(",");
                if(subImageArray.length > 0){
                    product.setMainImage(subImageArray[0]);
                }
            }
            if(product.getId() == null){
                //说明是一个增加
                int count = productMapper.insertSelective(product);
                if(count > 0){
                    return ServerResponse.createBySuccessMessage("新增产品成功");
                } else {
                    return ServerResponse.createByErrorMssage("新增产品失败");
                }
            } else{
                //是一个修改
                int count = productMapper.updateByPrimaryKeySelective(product);
                if(count > 0){
                    return ServerResponse.createBySuccessMessage("更新产品成功");
                } else {
                    return ServerResponse.createByErrorMssage("更新产品失败");
                }
            }
        }
        return ServerResponse.createByErrorMssage("产品service中参数传入错误");
    }

    //设置上下架状态
    public ServerResponse setSaleStatusService(Integer productId, Integer status){
        if(productId == null){
            return ServerResponse.createByErrorMssage(ResponseCode.NEED_LOGIN.getCode(), "参数错误");
        }
        Product product = new Product();
        product.setId(productId);
        product.setStatus(status);
        int count = productMapper.updateByPrimaryKeySelective(product);
        if(count > 0){
            return ServerResponse.createBySuccessMessage("更新成功");
        }
        return ServerResponse.createByErrorMssage("更新失败");
    }

    //获得单个商品详情
    public ServerResponse<ProductDetailVo> getProductDetail(Integer productId){
        if(productId == null){
            return ServerResponse.createByErrorMssage("参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    //生成一个product的详情vo
    private ProductDetailVo assembleProductDetailVo(Product product){
        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setId(product.getId());
        productDetailVo.setSubtitle(product.getSubtitle());
        productDetailVo.setPrice(product.getPrice());
        productDetailVo.setMainImage(product.getMainImage());
        productDetailVo.setSubImages(product.getSubImages());
        productDetailVo.setCategoryId(product.getCategoryId());
        productDetailVo.setDetail(product.getDetail());
        productDetailVo.setName(product.getName());
        productDetailVo.setStatus(product.getStatus());
        productDetailVo.setStock(product.getStock());

        productDetailVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        Category category = categoryMapper.selectByPrimaryKey(product.getCategoryId());
        if(category == null){
            productDetailVo.setParentCategoryId(0);
        } else {
            productDetailVo.setParentCategoryId(category.getParentId());
        }
        productDetailVo.setCreateTime(DateTimeUtil.dateToStr(product.getCreateTime()));
        productDetailVo.setUpdateTime(DateTimeUtil.dateToStr(product.getUpdateTime()));
        return productDetailVo;
    }

    public ServerResponse<PageInfo> selectAllProduct(int pageNum, int pageSize){
        // start page
        //填充自己的SQL查询逻辑
        //pagerhelper收尾
        PageHelper.startPage(pageNum, pageSize);
        List<Product> productList = productMapper.selectAllProduct();
        List<ProductListVo> productListVoList = Lists.newArrayList();
        if(productList.size() > 0){
            for(Product productItem : productList){
                ProductListVo productListVo = assembleProductListVo(productItem);
                productListVoList.add(productListVo);
            }
            PageInfo pageResult = new PageInfo(productListVoList);
            return ServerResponse.createBySuccess("取所有产品成功", pageResult);
        }
        return ServerResponse.createByErrorMssage("当前没有任何产品");
    }

    private ProductListVo assembleProductListVo(Product product){
        ProductListVo productListVo = new ProductListVo();
        productListVo.setId(product.getId());
        productListVo.setCategoryId(product.getCategoryId());
        productListVo.setMainImage(product.getMainImage());
        productListVo.setName(product.getName());
        productListVo.setPrice(product.getPrice());
        productListVo.setStatus(product.getStatus());
        productListVo.setSubtitle(product.getSubtitle());
        productListVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix", "http://img.happymmall.com/"));
        return productListVo;
    }

    public ServerResponse<PageInfo> productSearch(String productName, Integer productId, int pageNum, int pageSize){
        PageHelper.startPage(pageNum, pageSize);
        if(StringUtils.isNotBlank(productName))
            productName = new StringBuffer().append("%").append(productName).append("%").toString();
        List<Product> productList = productMapper.productSearch(productName, productId);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        if(productList.size() > 0){
            for(Product productItem : productList){
                ProductListVo productListVo = assembleProductListVo(productItem);
                productListVoList.add(productListVo);
            }
            PageInfo pageResult = new PageInfo(productListVoList);
            return ServerResponse.createBySuccess("搜索商品成功", pageResult);
        }
        return ServerResponse.createByErrorMssage("没找到该商品");
    }


    /**
     * 用户product
     */
    //获得单个商品详情
    public ServerResponse<ProductDetailVo> getProductDetailCustomer(Integer productId){
        if(productId == null){
            return ServerResponse.createByErrorMssage("参数错误");
        }
        Product product = productMapper.selectByPrimaryKey(productId);
        if(product.getStatus() != Const.ProductStatus.ON_SALE.getCode()){
            return ServerResponse.createByErrorMssage("产品已下架或已经删除");
        }
        ProductDetailVo productDetailVo = assembleProductDetailVo(product);
        return ServerResponse.createBySuccess(productDetailVo);
    }

    public ServerResponse<PageInfo> getProductByKeyWordCategoryId(String keyWord, Integer categoryId, int pageNum, int pageSize, String orderBy){
        if(StringUtils.isBlank(keyWord) && categoryId == null){
            return ServerResponse.createByErrorMssage("参数错误");
        }
        List<Integer> categoryIdList = new ArrayList<Integer>();
        //如果输入的类别ID不为空
        if(categoryId != null){
            Category category = categoryMapper.selectByPrimaryKey(categoryId);
            //查找出该类别，如果没有这个类别，且没有关键字，返回 一个空的结果集，不报错
            if(category == null && StringUtils.isBlank(keyWord)){
                PageHelper.startPage(pageNum, pageSize);
                List<Product> productList = Lists.newArrayList();
                PageInfo pageInfo = new PageInfo(productList);
                return ServerResponse.createBySuccess(pageInfo);
            }
            List<Category> categoryList = iCategoryService.getChildrenParallelCategoryService(categoryId).getData();
        }
        if(StringUtils.isNotBlank(keyWord)){
            keyWord = new StringBuilder().append("%").append(keyWord).append("%").toString();
        }
        PageHelper.startPage(pageNum, pageSize);
        if(StringUtils.isNotBlank(orderBy)){
            if(Const.ProductListOrderBy.PRICE_ASC_DESC.contains(orderBy)){
                String[] orderByArray = orderBy.split("_");
                PageHelper.orderBy(orderByArray[0] + " " + orderByArray[1]);
            }
        }
        List<Product> productList = productMapper.selectByNameAndCategoryIds(StringUtils.isBlank(keyWord)?null:keyWord,
                categoryIdList.size() == 0?null:categoryIdList);
        List<ProductListVo> productListVoList = Lists.newArrayList();
        for(Product product : productList){
            productListVoList.add(assembleProductListVo(product));
        }
        PageInfo pageInfo = new PageInfo(productListVoList);
        pageInfo.setList(productListVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }


}
